'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 对战记录
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var battleRecordSchema = require('../schemas/battleRecordSchema');
var BattleRecord = mongoConnector().model('BattleRecord');
var battleRewardService = require('../services/battleRewardService');

/**
 * 添加一个战斗记录
 */
module.exports.addRecord = function (atk_role_id, def_role_id, atk_data, def_data, battle_type, cb) {
    // 创建成功后
    function afterCreate(err, model) {
        cb(err, model);
    }

    BattleRecord.create({
        atk_role_id: atk_role_id,
        def_role_id: def_role_id,
        atk: atk_data,
        def: def_data,
        battle_type: battle_type,
        reward_list: _getBattleRandomReward(atk_data.job_type)
    }, afterCreate);
};

/**
 * 获取一个对战记录
 */
module.exports.getRecordByAtkRoleId = function (atk_role_id, record_id, cb) {
    BattleRecord.findById(record_id, function (err, battle_record_model) {
        if (!!battle_record_model && battle_record_model.getAtkRoleId() != atk_role_id) {
            cb(new Error('battle record not found'));
        } else {
            cb(null, battle_record_model);
        }
    });
};

/**
 * 获取战报列表
 * @param  {[type]}   atk_role_id [description]
 * @param  {[type]}   record_id   [description]
 * @param  {Function} cb          [description]
 * @return {[type]}               [description]
 */
module.exports.getRecordListByDefRoleId = function (def_role_id, cb) {
    BattleRecord
        .find({
            def_role_id: def_role_id
        })
        .limit(20)
        .sort('-create_time')
        .exec(cb);
};

/**
 * 获取战斗的随机奖励
 * @return {[type]} [description]
 */
var _getBattleRandomReward = function (job_type) {
    var reward_list = battleRewardService.getReward(job_type);
    for (var i = 0; i < 3; i++) {
        reward_list.push({});
    }
    return _.shuffle(reward_list);
};
